package com.dong.ch04_linkedList;

public class LinkedList<E> {
    public class Node<E> {
        E e;
        Node<E> next;

        public Node(E e, Node<E> next) {
            this.e = e;
            this.next = next;
        }
        public Node(E e) {
            this(e,null);
        }
        public Node() {
            this(null,null);
        }
    }
    Node head;
    int size =0;
    public int getSize() {
        return this.size;
    }
    public boolean isEmpty() {
        return size==0;
    }
    public void addFirst(E e) {
        head=new Node(e,head);
        size++;
    }
    public E get(int index) {
        Node<E> node =head;

        for (int i = 0; i < index; i++) {
            node=node.next;
        }
        return node==null?null:node.e;
    }
    public boolean contains(E e) {
        Node<E> node = head;
        while(node!=null) {
            if(node.e.equals(e)){
                return true;
            }
            node=node.next;
        }
        return false;
    }
    public void remove(E e) {
        Node<E> node = head;
        Node<E> pre=null;
        while(node!=null) {
            if(node.e.equals(e)){
               pre.next=node.next;
               node.next=null;
            }
            pre=node;
            node=node.next;
        }
    }
    public void add(E e,int pos) {
        if(pos<0||pos>size) {
            throw new IllegalArgumentException("add failed, illegal index");
        }
        if(pos==0) {
            addFirst(e);
        }else {
            Node pre = head;
            for (int i = 0; i < pos; i++) {
                pre=pre.next;
            }
            pre.next=new Node(e, pre.next);
            size++;
        }
    }
    public void addLast(E e) {
        add(e,size );
    }


}
